//
//  Tabbar.swift
//  HeadlineNews
//
//  Created by han on 2019/6/24.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

class Tabbar: UITabBar {
    
    var selectedIndex: Int
    
    var centerButton: UIButton?
    
    var isCenterButtonExist: Bool = false
    
    
    override init(frame: CGRect) {
        selectedIndex = 1
        super.init(frame: frame)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        for tabbarButton in self.subviews {
            guard let tabbarButton: UIControl = tabbarButton as? UIControl else { continue }
            if tabbarButton.isKind(of: NSClassFromString("UITabBarButton")!) {
                tabbarButton.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
            }
        }
        
        
    }
    
    func addCenterButton( actionClasure: @escaping (UIButton) -> Void) {
        isCenterButtonExist = true
        centerButton = UIButton(type: .custom)
        
    }
    
    
    
    @objc func buttonClick(sender: UIControl) {
       
        for imageView in sender.subviews {
            if imageView.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
                doAnimationWith(imageView)
            }
        }
//        guard let selectedItem = selectedItem else { return }
//        let index = items?.firstIndex(of: selectedItem)
//        self.selectedIndex = index
    }
    
    func doAnimationWith(_ view: UIView) {
        let animation = CAKeyframeAnimation()
        animation.keyPath = "transform.scale"
        animation.duration = 0.3
        animation.calculationMode = .cubicPaced
        animation.values = [1.0,1.1,0.9,1.0]
        view.layer.add(animation, forKey: nil)
    }
    
}

extension Tabbar: CAAnimationDelegate {
    func animationDidStart(_ anim: CAAnimation) {
        
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        
    }
}



